package codepulse.blogmoon.cn.system.dubbo;

import cn.dev33.satoken.stp.StpUtil;
import codepulse.blogmoon.cn.common.enums.ErrorCode;
import codepulse.blogmoon.cn.common.enums.StatusEnum;
import codepulse.blogmoon.cn.common.exception.BizException;
import codepulse.blogmoon.cn.system.dto.LoginReq;
import codepulse.blogmoon.cn.system.dto.LoginResp;
import codepulse.blogmoon.cn.system.entity.SysBizAccount;
import codepulse.blogmoon.cn.system.service.SysAccountInfoService;
import codepulse.blogmoon.cn.system.service.SysBizAccountService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@DubboService
public class AuthDubboServiceImpl implements AuthDubboService {

    @Autowired
    private SysBizAccountService sysBizAccountService;


    @Override
    public LoginResp login(LoginReq loginReq) {
        SysBizAccount sysBizAccount = sysBizAccountService.getOne(Wrappers.<SysBizAccount>lambdaQuery()
                .eq(SysBizAccount::getMobile, loginReq.getMobile()));
        if (Objects.isNull(sysBizAccount)) {
            throw new BizException(ErrorCode.LOGIN_ERROR.getCode(), "账户名不存在,请重新输入");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(loginReq.getPassword(), sysBizAccount.getPassword())) {
            throw new BizException(ErrorCode.LOGIN_ERROR.getCode(), "密码不正确,请重新输入");
        }
        StpUtil.login(sysBizAccount.getId());

        return LoginResp.builder().token(StpUtil.getTokenValue()).build();
    }
}
